<?php
include_once "../../qc_base.php";
include_once "../../qc_utils.php";
include_once "../../bootstrap.php";

include_once "../../classes/MakePage.php";


/**
   * This file contains the class
   * @package phpnewmaker
   */
   


function makesuredir($dir){
	if(!file_exists(dirname($dir))){
		makesuredir(dirname($dir));
	}
	if(!file_exists($dir)){
		mkdir($dir);
	}
}


function write_pdoaj_form_to_file($crudset_id){


// ------------- Get data sets from database --------

/*  crudset data in $setinfo[<var>]
var:
	crudset_id 
	cs_name 
	paging 
	sorting 
	filter 
	main_table 
	project_id 
	query 
	cs_type 
	list_base_name 
	proc_base_name 
	process_class 
	class_base_name 
	html_table_name 
	class_name 
	list_table_instance 
	proc_class_instance 
	edit_base_class 
	edit_class_name 
	edit_instance 
	edit_page_name 
	multiact 
	css_file 
	showbuttons 
	subdirectory 
	needs_login 
*/

	$qcs = Doctrine_Query::create()
	->from('Crudsets cs')->where('crudset_id = ?',$crudset_id);
	$setinfo = $qcs->fetchOne();

/* Tablesource Data
$tablesource[<var>]
$tablename = $tablesource['table_name']
var:
	tablesource_id 
	project_id 
	table_name 
	table_alias 
	table_filter 
*/
	// get the main table for the set
	$qtb = Doctrine_Query::create()
	->from('Tablesources tb')->where('tablesource_id = ?',$setinfo['main_table']);
	$tablesource = $qtb->fetchOne();
	$table_name = $tablesource['table_name'];

/*
	Projects data
	$project[<var>]
	var:
		project_id 	int(10) unsigned 	NO 	PRI 	NULL 	auto_increment
		project_name 	varchar(45) 	YES 	  	autoproj 	 
		def_function_page 	varchar(45) 	YES 	  	NULL 	 
		project_path 	varchar(255) 	YES 	  	autoproj 	 
		project_server 	varchar(45) 	YES 	  	NULL 	 
		project_db 	varchar(45) 	YES 	  	NULL 	 
		project_login 	varchar(45) 	YES 	  	NULL 	 
		project_pass 	varchar(45) 	YES 	  	NULL 	 
		class_subpath 	varchar(40) 	NO 	  	CFClass 	 
		user_table_name 	varchar(40) 	NO 	  	users 	 
		up_table_name 	varchar(40) 	NO 	  	users_pages 	 
		dbmethod 	varchar(20) 	NO 	  	pdo 	 
		dbtype 	varchar(20) 	NO 	  	mysql 	 
		template_dir 	varchar(255) 	NO 	  	templates/default/ 	 
		file_structure 	varchar(40) 	NO 	  	NULL 	 

*/

	$q = Doctrine_Query::create()
	->from('Projects p')->where('project_id = ?',$setinfo['project_id']);
	$project = $q->fetchOne();	

/*
Crudcols - Array of all crudcol specifiers
$cruscols[<index>][<var>]
(loop through each)
var:
	crudcol_id 	int(10) unsigned 	NO 	PRI 	NULL 	auto_increment
	crudset_id 	int(10) unsigned 	YES 	  	NULL 	 
	variable_id 	int(11) 	YES 	  	NULL 	 
	is_key 	smallint(5) unsigned 	YES 	  	0 	 
	shown_in_list 	smallint(6) 	NO 	  	1 	 
	edit_in_list 	smallint(6) 	YES 	  	1 	 
	edit_type 	varchar(20) 	NO 	  	text 	 
	filter 	tinyint(4) 	YES 	  	0 	 
	showfilter 	tinyint(20) 	NO 	  	0 	 
	restrict 	smallint(6) 	NO 	  	NULL 	 
	is_sort 	smallint(5) unsigned 	YES 	  	0 	 
	header_name 	varchar(45) 	YES 	  	NULL 	 
	is_add 	varchar(45) 	YES 	  	0 	 
	list_query 	text 	YES 	  	NULL 	 
	list_keycol 	varchar(45) 	YES 	  	NULL 	 
	list_showcol 	varchar(45) 	YES 	  	NULL 	 
	size 	int(11) 	NO 	  	20 	 
	rows 	int(11) 	NO 	  	1 	 
	col_order 	int(11) 	NO 	  	NULL 	 
	makefunction 	varchar(20) 	NO 	  	NULL 	


	var_name (name of variable)
	var_info = array of variable information
*/	
	
	$qcc = Doctrine_Query::create()
	->from('Crudcols c')->where('crudset_id = ?',$setinfo['crudset_id']);
	$crudcols = $qcc->execute()->toArray();

	//print_r($crudcols);
	//exit;
	
	foreach($crudcols as $key=>$crudcol){
		//echo 'Looking up ' . $crudcol['variable_id'];
		$qv = Doctrine_Query::create()
		->from('Variables v')->where('variable_id = ?',$crudcol['variable_id']);
		$varsrecord = $qv->fetchOne();
		$crudcols[$key]['var_info'] = $varsrecord;	
		$crudcols[$key]['var_name'] = $varsrecord['variable_name'];
		//echo "<br> crudcol $key = " . $varsrecord['variable_name'] . '<br />';
	}
	
// ---------------End Get Data ---------------------

// ---------------Setup Files ----------------------
	$structure_path = QC_SYS_BASEDIR . '/structures/';
	
	include $structure_path . $structure .'/paths.php';
	

	$outpath = $paths['modules'];
	$outpath = str_replace('<setname>',$setinfo['cs_name'],$outpath);
	
	$outpath = QC_SYS_BASEDIR . '/' . QC_PROJECT_SUBPATH . $project['project_name'] . '/' . $outpath ;

	makesuredir($outpath);
	
	
	$targetfile = $outpath . $setinfo['cs_name'] . '_ajform.php';
	$tplfile = 'pdoaj_form_tpl.php';

	
//--------------------Create Replacement Text

// select control class from edit type
$ar_controltype['text']='CtlText';
$ar_controltype['querylist']='CtlSelect';
$ar_controltype['commalist']='CtlSelect';
$ar_controltype['checkbox']='CtlCheckbox';
$ar_controltype['calendar']='CtlJQDate';
$ar_controltype['textarea']='CtlTextArea';

$FormStart = "
<form name='frm_" . $setinfo['cs_name'] . "' id='frm_" . $setinfo['cs_name'] . "'  method='post' action=''>
";

$FormSel = '
<input type="hidden" value="' . $setinfo['cs_name'] . '" name="sel" />
';

$BindForm = "
	$('#frm_" . $setinfo['cs_name'] . "').bind('submit',function() { 
		var data = $(this).serialize();
		//alert(data);
		$.get('" . $setinfo['cs_name'] . "/" . $setinfo['cs_name'] . "_proc.php?' +  data,function(responce){
			//alert(responce.status);
			},'json');
	  return false;
	  }
	);
";

$AddHandler = "
function SE_Add_" . $setinfo['cs_name'] . "_form(valuekey){

	var url_values = null;
	var ar_url_lists = [];
	";
	foreach($crudcols as $index=>$crudcol){
		if($crudcol['edit_type'] == 'querylist'){
		$AddHandler .= "
		ar_url_lists[" . $crudcol['var_name'] . "] = '" . $setinfo['cs_name'] . "/" .  $setinfo['cs_name'] . "_proc.php?mode=jsonlookup&sel=";
		$AddHandler .= $setinfo['cs_name'] . "&col=" . $crudcol['var_name'] . "';\n";
		}
	}
$AddHandler .= "
	$('#frm_" . $setinfo['cs_name'] . "')[0].reset();
	$('#frm_" . $setinfo['cs_name'] . "').append(\"<input type='hidden' name='mode' value='Add' />\").find(':submit').val('Add');
	
	SetupForm('frm_" . $setinfo['cs_name'] . "',url_values,ar_url_lists);	
}
";

$EditHandler = "
function SE_Edit_" . $setinfo['cs_name'] . "_form(valuekey){

var keyset = ";
	$firstkey = true;
	foreach($crudcols as $index=>$crudcol){
		if($crudcol['is_key'] == 1){
			if($firstkey){
			$EditHandler .= '"' . $crudcol['var_name'] . '"';
			}else{
			$EditHandler .= ',' . '"' . $crudcol['var_name'] . '"';
			}
		}
	}
	$EditHandler .= ";\n";

	$EditHandler .= 'var url_values = "' . $setinfo['cs_name'] . '/' . $setinfo['cs_name'] . '_proc.php?mode=jprow&sel=' . $setinfo['cs_name'] . '&jsoncallback=?&ks=" + keyset + "&kv=" + valuekey;';

	foreach($crudcols as $index=>$crudcol){
		if($crudcol['edit_type'] == 'querylist'){
		$EditHandler .= "
		ar_url_lists[" . $crudcol['var_name'] . "] = '" . $setinfo['cs_name'] . "/" .  $setinfo['cs_name'] . "_proc.php?mode=jsonlookup&sel=";
		$EditHandler .= $setinfo['cs_name'] . "&col=" . $crudcol['var_name'] . "';\n";
		}
	}
$EditHandler .= "
	$('#frm_" . $setinfo['cs_name'] . "').append(\"<input type='hidden' name='mode' value='Change' />\").find(':submit').val('Change');
	
	SetupForm('frm_" . $setinfo['cs_name'] . "',url_values,ar_url_lists);	
}
";
	$ctls .= "<ul>\n";
	foreach($crudcols as $key=>$crudcol){
		if(!empty($crudcol['shown_in_list'])){
		$ctls .= '<li>
		<label for="' . $crudcol['var_name']. '" >' . $crudcol['var_name'] . '</label>
		';
		
			if(empty($crudcol['edit_in_list'])){
				$ctls .= '
				<span name="' . $crudcol['var_name'] . '" ></span>
				';			
			}else{
				$spec['name'] = $crudcol['var_name'];
				$ctls .= MakePhpCtl($ar_controltype[$crudcol['edit_type']],$spec);
				$ctls .= "</li>\n";
			}
		}
	
	}
	$ctls .= "</ul>";

	
//---------------------------Write into file	
	
	

	$pagemaker = new MakePage();

	$pagemaker->AddReplacement('FormStart',$FormStart);
	$pagemaker->AddReplacement('ctls',$ctls);	
		
	$pagemaker->AddReplacement('FormSel',$FormSel);
	$pagemaker->AddReplacement('BindForm',$BindForm);
	$pagemaker->AddReplacement('AddHandler',$AddHandler);
	$pagemaker->AddReplacement('EditHandler',$EditHandler);
	
	$newstuff = $pagemaker->ReplaceInFile($tplfile,$targetfile);
	
	$pagemaker->PrintReplacementsTable();

	echo '<pre>' . $pagemaker->str_log . '</pre>';
	
	file_put_contents($targetfile,$newstuff);	

	return $newstuff;


}
?>
